﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.IO;

namespace WhileAwayWpf
{
    public class AwayMessageCollection : ObservableCollection<AwayMessage>
    {
        static string saveFolder, fn;

        static AwayMessageCollection()
        {
            saveFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WhileAway");
            fn = Path.Combine(saveFolder, "Messages.dat");
        }

        public bool Save()
        {
            Directory.CreateDirectory(saveFolder);

            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(AwayMessageCollection));
                using (StreamWriter str = new StreamWriter(fn))
                {
                    ser.Serialize(str, this);
                    str.Close();
                }
                return true;
            }
            catch { }

            return false;
        }

        public void LoadFromDisk()
        {
            if (!File.Exists(fn)) return;

            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(AwayMessageCollection));
                using (StreamReader str = new StreamReader(fn))
                {
                    AwayMessageCollection toLoad = (AwayMessageCollection)ser.Deserialize(str);

                    foreach (AwayMessage msg in toLoad)
                        this.Add(msg);
                }
            }
            catch { }
        }

    }
}
